package org.duoyi.striver.model.impl;

import com.develop.jawin.COMException;
import lombok.extern.slf4j.Slf4j;
import org.duoyi.jdm.Dm.DmInstant;
import org.duoyi.striver.global.DmManager;
import org.duoyi.striver.model.Point;
import org.duoyi.striver.proxy.ProxyFactory;
import org.duoyi.striver.proxy.annotation.Delay;

/**
 * 坐标点
 *
 * @author chenyuheng create class on 2021-05-08
 */
@Slf4j
public class PointImpl implements Point {

    private int x;

    private int y;

    private static final ThreadLocal<Point> instantMap = new ThreadLocal<>();

    private PointImpl(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public static Point on(int x, int y) {
        Point instant = instantMap.get();
        if (instant != null) {
            instant.reset(x, y);
            return instant;
        }
        Point point = new PointImpl(x, y);
        instant = ProxyFactory.proxy(point);
        instantMap.set(instant);
        return instant;
    }

    public static void destroy() {
        instantMap.remove();
    }

    @Delay
    @Override
    public boolean moveTo() {
        DmInstant dmInstant = DmManager.get();
        try {
            dmInstant.MoveTo(x, y);
        } catch (COMException e) {
            log.error("移动鼠标到【{}, {}】失败", x, y);
            return false;
        }
        return true;
    }

    @Override
    public Point addR(int x, int y) {
        this.x += x;
        this.y += y;
        return this;
    }

    @Override
    public void reset(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Delay
    @Override
    public boolean leftClick() {
        if (!moveTo()) {
            return false;
        }
        DmInstant dmInstant = DmManager.get();
        try {
            Sleeper.sleep();
            dmInstant.LeftClick();
        } catch (COMException e) {
            log.error("左击【{}, {}】失败", x, y);
            return false;
        }
        return true;
    }
}
